package cn.edu.zafu.bigdata.hzq;

import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SERVER1 {
    public static void main(String[] args) {
        int port = 12345; // 服务端监听的端口
        try (DatagramSocket socket = new DatagramSocket(port)) {
            System.out.println("Server is listening on port " + port);

            while (true) {
                byte[] receiveData = new byte[1024];
                byte[] sendData = new byte[1024];
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                socket.receive(receivePacket);

                // 获取客户端的IP地址和端口
                InetAddress clientAddress = receivePacket.getAddress();
                int clientPort = receivePacket.getPort();

                // 获取当前系统时间
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String currentTimeStr = sdf.format(new Date());

                // 将时间字符串转换为字节
                sendData = currentTimeStr.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
                socket.send(sendPacket);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}